package unseen.games.taptap;

import java.util.HashMap;
import java.util.Stack;

import unseen.games.activity.GenericActivity;
import unseen.games.ui.manager.HighScoreManager;
import unseen.games.ui.manager.IngameManager;
import unseen.games.ui.manager.MainMenuManager;
import unseen.games.ui.manager.SettingsManager;
import unseen.games.utils.ConnectivityUtils;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.RelativeLayout;
import android.widget.ViewAnimator;

public class MainActivity extends GenericActivity {
	

	private ViewAnimator mViewAnimator;
	
	private HashMap<Integer, Stack<Integer>> screensHistory;
	
	private static final int MAIN_MENU 		= 0;
	private static final int INGAME			= 1;
	private static final int HIGH_SCORES	= 2;
	private static final int SETTINGS		= 3;
	
	private static final String FILENAME 	= "mytaptapscores";

	private MainMenuManager mMainMenuManager;
	private IngameManager mIngameManager;
	private HighScoreManager mHighScoreManager;
	private SettingsManager mSettingsManager;
	
	private View mSplashImage;
	
	private static ConnectivityUtils mConnectivityUtils;
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.generic_screen);
        
        screensHistory = new HashMap<Integer, Stack<Integer>>();
        
        initView();

        initManager();
        
        mConnectivityUtils = new ConnectivityUtils(this);
        new InitAsyncTask().execute();
    }

	private void initView() 
	{
		mSplashImage 	= (RelativeLayout) findViewById(R.id.splash);
		mViewAnimator = (ViewAnimator) findViewById(R.id.view_animator);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
	}
	
	private void initManager() 
	{
		mMainMenuManager 	= new MainMenuManager(this, findView(R.id.main_menu, "main_menu_stub"));
		mIngameManager 		= new IngameManager(this, findView(R.id.ingame, "ingame_stub"));
		mHighScoreManager	= new HighScoreManager(this, findView(R.id.high_score, "high_score_stub"));
		mSettingsManager	= new SettingsManager(this, findView(R.id.settings, "settings_stub"));
		
		showMainMenu();
	}
	
	 /**
	 * 
	 * ASYNC TASK
	 * 
	 */
	private class InitAsyncTask extends AsyncTask<Void, Void, Void>{
		@Override
		public Void doInBackground(Void...notUsed)
		{
			
			// TODO Do things more interesting than sleeping, like check for internet connection
			try {
				Thread.sleep(3000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			
			return null;
		}
		
		@Override
		public void onPostExecute(Void notUsed)
		{
			hideSplash();
		}
	}
	
	private void hideSplash()
	{
		mSplashImage.setVisibility(View.GONE);
		mViewAnimator.setVisibility(View.VISIBLE);
	}
	
	/////////////////////
	
	public void showGameScreen(){
		mIngameManager.initGame();
		mViewAnimator.setDisplayedChild(INGAME);
	}
	
	public void showMainMenu(){
		saveInHistory();
		mViewAnimator.setDisplayedChild(MAIN_MENU);
	}
	
	public void showHighScores(int score, boolean save) {
		mHighScoreManager.showHighScores(score, save);
		mViewAnimator.setDisplayedChild(HIGH_SCORES);
	}
	
	public void showSettings() {
		mViewAnimator.setDisplayedChild(SETTINGS);
	}
		
	public void saveInHistory()
	{
		int current = mViewAnimator.getDisplayedChild();
		
		if(screensHistory.get(0) == null){
			screensHistory.put(0, new Stack<Integer>());
		}
		
		// if the current view is already in the stack and is on top, no need to
		// add
		if (screensHistory.get(0) != null && !screensHistory.get(0).isEmpty()
				&& screensHistory.get(0).peek() == current) {
			return;
		}		
		screensHistory.get(0).push(current);
		Log.d("SAVE HISTORY", current + "");
	}
	

	public void resetScore(){
		deleteFile(FILENAME);
	}

	/**
	 * Display the previous screen in history or exit the application if there
	 * is no more views in the history
	 */
	public void goBackInHistory(boolean fromKey) 
	{
		int id = 0;
		
		if(fromKey){
			if(screensHistory.get(id) == null || screensHistory.get(id).isEmpty()){
				
				AlertDialog.Builder builder = new AlertDialog.Builder(this);
				builder.setMessage(R.string.global_sure_to_quit)
				       .setCancelable(false)
				       .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
				           public void onClick(DialogInterface dialog, int id) {
				        	   MainActivity.this.finish();
				           }
				       })
				       .setNegativeButton("No", new DialogInterface.OnClickListener() {
				           public void onClick(DialogInterface dialog, int id) {
				        	   setCurrentView(MAIN_MENU);
				               dialog.cancel();
				           }
				       });
				AlertDialog alert = builder.create();
				alert.show();
			}
			else{				
				int nextIndex = screensHistory.get(id).pop();
				
				setCurrentView(nextIndex);
			}
		}
		else{
			int nextIndex = screensHistory.get(id).pop();
			setCurrentView(nextIndex);
		}
	}
		
	public void setCurrentView(int viewIndex) 
	{
		mViewAnimator.setInAnimation(null);
		mViewAnimator.setOutAnimation(null);		
		
		mViewAnimator.setDisplayedChild(viewIndex);
	}
	
	@Override
	public void onConfigurationChanged(Configuration newConfig) 
	{
		super.onConfigurationChanged(newConfig);
	}
			
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) 
	{
		Log.d("TAG", "onKeyDown");
		int currentDisplayedChild = mViewAnimator.getDisplayedChild();
		
		if (keyCode == KeyEvent.KEYCODE_BACK) 
		{
			goBackInHistory(true);
			return true;
		}
		else if (keyCode == KeyEvent.KEYCODE_MENU) 
		{
			return true;
		}
		else if (keyCode == KeyEvent.KEYCODE_SEARCH) 
		{
			onSearchRequested();
			return true;
		}
		else 
		{
			return super.onKeyDown(keyCode, event);
		}
	}

	/**
	 * @return the mConnectivityUtils
	 */
	public static ConnectivityUtils getConnectivityUtils() {
		return mConnectivityUtils;
	}



}